var layer;
var form;
var table;
var tree;
var treeSelect;
var treeTable;

/**	
 * layui 组件引入
 * @returns
 */
layui.use([ 'layer', 'form', 'table', "treeSelect", 'tree', "treeTable"], function() {
	layer = layui.layer;
	form = layui.form;
	table = layui.table;
	tree = layui.tree;
	treeSelect = layui.treeSelect;
	treeTable = layui.treeTable;
	
	// 加载字典=======================================================================================================
    getDictLabel("use_state", "#state", "state", true);
    getDictLabel("use_state", "#search_state", "state", false, 3);
	getDictLabel("role_type", "#type", "type", true);
	getDictLabel("role_type", "#search_type", "type", false, 3);
    
    // 执行一个 table 实例=============================================================================================
	table.render({
		elem : '#data_table', 
		id : 'data_table', 
		url : ctxPath+'sys/role/select',
		title : '数据列表',
		//height:'full-120',
		skin:'line',
		page : true,
		toolbar : "#toolberLeft",
		cols : [ [
			{type : 'checkbox', fixed : ''},
			{field : 'rname', title : '角色名称', width: '180', align : 'center', hide: setColumnHide("rname"), edit: 'text'},
			{field : 'state', title : '使用状态', width: '180', align : 'center', hide: setColumnHide("state"), toolbar : '#switchRow'},
			{field : 'type', title : '类型', width: '180', sort : true, align : 'center', hide: setColumnHide("type"), templet: function (d){return getDictText("role_type",d.type)}},
			{field : 'createDate', align : 'center', width: '200', title : '创建时间', hide: setColumnHide("createDate")},
			{field : 'updateDate', align : 'center', width: '200', title : '更新时间', hide: setColumnHide("updateDate")},
			{field : 'remarks', align : 'center', width: '300', title : '备注', hide: setColumnHide("remarks")},
			{fixed : isRight(), align : 'center', width: '350', title : '操作', toolbar : '#toolRow'}
		] ]
		, done: function (result, currPage, count) {
		}
	});

	// 监听单元格编辑============================================================================================
	table.on('edit(data_table)', function(obj){
		var value = obj.value //得到修改后的值
			,data = obj.data //得到所在行所有键值
			,field = obj.field; //得到字段
		var obj = {"rid": data.rid};
		obj[field] = value;
		saveData(table, 'data_table', obj, ctxPath+'sys/role/save', '#data_form');
	});
    
	// 头部左侧事件=============================================================================================
	table.on('toolbar(data_table)',  function(obj) {
		if (obj.event === 'search') {
			openWindowSearch('search_form', "条件搜索", '100%', 'auto', false, 0, false, false, null, 0.2, true)
		}else if(obj.event === 'add'){
			openWindow('data_form', "角色新增", '450px', '480px', false, 0, false, false, null, 0.2, false)
		}else if(obj.event === 'delete'){
            deleteBatch(table, 'data_table', "rid", ctxPath+'sys/role/deleteBatch')
		}
	})
	
	// 行监听事件=============================================================================================
	table.on('tool(data_table)',  function(obj) {
		var data = obj.data;
		if (obj.event === 'del') {
			deleteRow(table, 'data_table', data, ctxPath+'sys/role/delete'+"?rid="+data.rid);
		}else if(obj.event === 'edit') {
			openWindow('data_form', "角色编辑", '450px', '480px', false, 0, false, false, data, 0.2, false)
		}else if(obj.event === 'detail') {
			openWindow('data_form', "角色查看", '450px', '480px', false, 0, false, false, data, 0.2, false)
		}else if(obj.event === 'power') {
			openWindowRB('role_menu_form', "授权菜单", '500px', '100%', false, 0, false, false, data, 0.2, false, function(res){
				getAjax(ctxPath+"sys/role/selectRoleMenuTree", {rid: res.rid}, 'get', function (res) {
			        if (res.success) {
			        	var list = [{"id": 0, "title": "全选", "spread": true, children: res.data}];
			        	tree.render({
			        		elem: '#menu_tree'
			        		,data: list
							,showCheckbox: true  //是否显示复选框
							,id: 'menu'
			        	});
			        }else{
			        	showTips(res.msg);
			        }
			    })
			})
		}else if (obj.event === 'power_operation') {
			openWindowRB('role_menu_operation_form', '授权菜单按钮', '760px', '100%', false, 0, false, false, data, 0.2, false, function(res){
				$.post(ctxPath+"sys/dict/getDictSetting",{"code": 'role_btn'},function(res){
					if(res.success){
						var colsList = [
							{type : 'checkbox', fixed : 'left', hide: true},
							{field: 'mname', width: 240, title: '菜单名称'}
						]
						$("#checkBox").empty();
						var array = res.data;
						for (var i=0; i<array.length; i++){
							var obj = array[i];
							setcolsList(colsList, obj.code, obj.remarks);
							checkAll(obj.code, obj.remarks);
						}
						treeTable.render({
							elem: '#role_menu_operation_table',
							id: 'role_menu_operation_table',
							url:  ctxPath+"sys/role/selectRoleMenuOperation"+'?rid=' + data.rid + "&code=role_btn",
							height:'full-280',
							page: false,
							treeColIndex: 1,	// 树形图标显示在第几列
							treeSpid: 0,		// 最上级的父级id
							treeIdName: 'mid',	// id字段的名称
							treePidName: 'parentId',// pid字段的名称
							treeDefaultClose: false,// 是否默认折叠
							treeLinkage: true,		// 父级展开时是否自动展开所有子级
							cols : [colsList]
							,done:function(result,currPage,count){//数据回调方法
								//var data = result.data;
								form.render();
							},
						});

						// 提交=============================================================================================
						form.on('submit(menuOperationForm)',  function(data) {
							var rid = data.field.rid;
							var list = [];
							for (var i=0; i<array.length; i++){
								var obj = array[i];
								getCheck(list, '.'+obj.code+'_class', rid, obj.code)
							}
							var text = sbumitLoading('#role_menu_form .lay-submit-btn');
							getAjax(ctxPath+"sys/role/saveRoleMenuOperation", JSON.stringify({rid: rid, list: list}), 'post', function (res) {
								if (res.success) {
									layer.closeAll();
								}
								showTips(res.msg);
								closeLoading('#role_menu_form .lay-submit-btn', text)
							}, '','application/json')
							return false;
						})
					}
				})

			});
		}
	});
	
	// 查询=============================================================================================
	form.on('submit(submitSearch)',  function(data) {
		reloadTable(table, 'data_table', data.field);
		return false;
	})
	
	// 提交=============================================================================================
	form.on('submit(submitForm)',  function(data) {
		saveData(table, 'data_table', data.field, ctxPath+'sys/role/save', '#data_form');
		return false;
	})
    
	// 提交角色菜单=============================================================================================
	form.on('submit(roleMenuForm)', function(data) {
		var rid = data.field.rid;
		var checkData = tree.getChecked('menu');
	    var mids = [];
	    getTreeValue(checkData, mids);
	    var text = sbumitLoading('#role_menu_form .lay-submit-btn');
	    getAjax(ctxPath+"sys/role/saveRoleMenu", {mids: mids.join(","), rid: rid}, 'post', function (res) {
	        if (res.success) {
	            layer.closeAll();
	        }
	        showTips(res.msg);
	        closeLoading('#role_menu_form .lay-submit-btn', text)
	    })
	    return false;
	})
    
	// 开关=============================================================================================
	form.on('switch(stateSwitch)', function(data) {
		var rid = $(this).attr('rid');
	    var state = data.elem.checked?"1":"0";
	    getAjax(ctxPath+"sys/role/updateState", {rid: rid, state: state}, 'post', function (res) {
	    	showTips(res.msg);
	    })
		return false;
	})




	
})



/**
 * 字典表格列（按钮权限）
 * ---------------------------------------------------------------------------------------------------------------------
 * @param label
 */
function setcolsList(colsList, code, remarks) {
	colsList.push({field: code + 'State', width: 80, title: remarks,
		templet: function (d) {
			return tableSelect(d, code);
		}
	})
}

/**
 * 表格行是否选中（按钮权限）
 * ---------------------------------------------------------------------------------------------------------------------
 * @param label
 */
function tableSelect(d, label) {
	return '<div class="'+label+'_class"><input '+(d[label+'State']>0?"checked":"")+' type="checkbox" lay-id="'+d.mid+'" name="'+label+'" lay-skin="primary" title=""></div>';
}

/**
 * 全选（按钮权限）
 * ---------------------------------------------------------------------------------------------------------------------
 * @param label
 */
function checkAll(label, name) {
	var s = '<span>' +
		'<input type="checkbox" name="'+label+'All" lay-filter="'+label+'All" lay-skin="primary" title="'+name+'全选">' +
		'</span>';
	$("#checkBox").append(s);
	form.render();
	form.on('checkbox('+label+'All)', function(data){
		if(data.elem.checked == true){
			$('.'+label+'_class').children('div').addClass('layui-form-checked');
			$('.'+label+'_class input').prop("checked", true);
		}else{
			$('.'+label+'_class').children('div').removeClass('layui-form-checked');
			$('.'+label+'_class input').prop("checked", false);
		}
	});
}



/**
 * ---------------------------------------------------------------------------------------------------------------------
 * 获取菜单按钮选中权限
 * @param list
 * @param lable
 * @param rid
 * @param type
 * @returns {*}
 */
function getCheck(list, lable, rid, type) {
	var check = $(lable+' input[type=checkbox]');
	check.each(function (index, item) {
		if(item.checked){
			var mid = $(this).attr("lay-id");
			list.push({"rid": rid, "mid": mid, "operation": type})
		}
	});
	return list;
}


/**
 * ---------------------------------------------------------------------------------------------------------------------
 * 获取菜单选中值
 */
function getTreeValue(list, mids){
	$(list).each(function (i, o) {
		if(o.id > 0){
			mids.push(o.id);
		}
		getTreeValue(o.children, mids);
    });
}



